#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   schema.py
@Time    :   2024/02/19 16:03:21
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from pydantic import validator
from datetime import datetime
from typing import List, Optional, Type, Any
from django.db import transaction
from ninja_extra import service_resolver
from ninja_extra.controllers import RouteContext
from ninja_extra.exceptions import APIException

from django.contrib.auth import get_user_model
from ninja import Field
from ninja_schema import ModelSchema, Schema, model_validator
from core.schemas import CoreModelSchema
from .models import Role,ClassModel

# 获取用户模型
UserModel = get_user_model()


# Role显示字段
class RoleSchema(ModelSchema):
    class Config:
        model = Role
        include = ("name", "tag")
        
class ClassSchema(ModelSchema):
    class Config:
        model = ClassModel
        include = ("id", "name", "tag", "description")

class CreatRoleSchema(CoreModelSchema):
    class Config:
        model = Role
        include = ("name", "tag", "description")

    @model_validator("tag")
    def unique_tag(cls, value_data):
        context: RouteContext = service_resolver(RouteContext)
        if not Role.objects.filter(tag=value_data).exists():
            return value_data
        elif context.kwargs.get("c_id"):
            if Role.objects.filter(
                tag=value_data, id=context.kwargs.get("c_id")
            ).exists():
                return value_data
        raise APIException("角色tag已存在")

    @transaction.atomic
    def create_obj(self, **kwargs: Any):
        _data = self.dict(exclude_none=True)
        _data.update(kwargs)
        return Role.objects.create(**_data)
    
    
class CreateClassSchema(CoreModelSchema):
    class Config:
        model = ClassModel
        include = ("name", "tag", "description")
        
    @model_validator("tag")
    def unique_tag(cls, value_data):
        context: RouteContext = service_resolver(RouteContext)
        if not ClassModel.objects.filter(tag=value_data).exists():
            return value_data
        elif context.kwargs.get("c_id"):
            if ClassModel.objects.filter(
                tag=value_data, id=context.kwargs.get("c_id")
            ).exists():
                return value_data
        raise APIException("班级tag已存在")
        
    @transaction.atomic
    def create_obj(self, **kwargs: Any):
        _data = self.dict(exclude_none=True)
        _data.update(kwargs)
        return ClassModel.objects.create(**_data)


# 用户登录请求字段
class LoginSchema(Schema):
    username: str = Field(..., description="用户名")
    password: str = Field(..., description="密码")


class UserInfoSchema(ModelSchema):
    role: RoleSchema | None

    class Config:
        model = UserModel
        include = ("id", "username", "nickname", "email", "status")


class UserTokenOutSchema(Schema):
    token: str
    user: UserInfoSchema
    token_exp_date: Optional[datetime]
